﻿namespace DimensionsHelper.CommandLine.ConsoleTracer;

internal static class ConsoleHelper
{
    public static void SetCursorPosition(in ConsolePosition position)
    {
        Console.SetCursorPosition(position.Character, position.Line);
    }


    public static void SetCursorPosition(int line)
    {
        Console.SetCursorPosition(0, line);
    }


    public static ConsolePosition Write(string content)
    {
        Console.Write(content);
        return ConsolePosition.Create(Console.CursorTop, Console.CursorLeft);
    }


    public static ConsolePosition Write(string content, ConsoleColor? foreground, ConsoleColor? background = null)
    {
        if (foreground != null)
        {
            Console.ForegroundColor = (ConsoleColor)foreground;
        }

        if (background != null)
        {
            Console.BackgroundColor = (ConsoleColor)background;
        }

        ConsolePosition pos = Write(content);
        Console.ResetColor();
        return pos;
    }


    public static void WriteSpace(int count)
    {
        Console.Write(new string(' ', count));
    }


    public static void ClearLine(int line)
    {
        if (line < 0)
        {
            return;
        }

        SetCursorPosition(line);
        WriteSpace(Console.WindowWidth);
    }


    public static void ClearText(ConsoleLocation location)
    {
        if (!location.Validate())
        {
            return;
        }

        int lines = location.GetLines();

        if (lines == 1)
        {
            SetCursorPosition(location.Start);
            WriteSpace(location.End.Character - location.Start.Character);
        }
        else
        {
            int startLine = location.Start.Line;

            while (lines > 1)
            {
                ClearLine(startLine++);
                lines--;
            }

            SetCursorPosition(location.End.Line);
            WriteSpace(location.End.Character);
        }
    }
}